<?php
/**
 * System_Model_DbTable_EmployeeRole
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: EmployeeRole.php 906 2011-10-20 02:38:33Z mmxie $
 */
class System_Model_DbTable_EmployeeRole extends IG_Model_DbTable
{

    protected $_name = 'sys_employee_role';

    protected $_primary = 'role_id';

    protected $_referenceMap = array(
        'Role' => array(
            'columns' => 'role_id',
            'refTableClass' => 'System_Model_DbTable_Role',
            'refColumns' => 'role_id'
        ),
        'Employee' => array(
            'columns' => 'employee_id',
            'refTableClass' => 'System_Model_DbTable_Employee',
            'refColumns' => 'employee_id'
        )
    );

    public function getEmployeeByRole($roleId)
    {

        return $this->select()->setIntegrityCheck(false)
                    ->from($this->_name, array('employee_id'))
                    ->join('sys_employee', "$this->_name.employee_id = sys_employee.employee_id", array('real_name'))
                    ->where("$this->_name.role_id=?", $roleId)
                    ->query(PDO::FETCH_KEY_PAIR)->fetchAll()
                    ;
    }

    public function getRoleByEmployee($employeeId)
    {
        return $this->select()->setIntegrityCheck(false)
                    ->from($this->_name, array('role_id'))
                    ->join('sys_role', "$this->_name.role_id = sys_role.role_id", array('name'))
                    ->where("$this->_name.employee_id=?", $employeeId)
                    ->query(PDO::FETCH_KEY_PAIR)->fetchAll()
                    ;
    }

    public function saveRoleEmployee($roleId, $employees)
    {
        $this->delete(array('role_id=?' => $roleId));
        foreach ($employees as $employee) {
            $this->insert(array(
                'role_id' => $roleId,
                'employee_id' => $employee
            ));
        }
    }

    public function saveEmployeeRole($employeeId, $roles)
    {
        $this->delete(array('employee_id=?' => $employeeId));

        foreach ($roles as $role) {
            $this->insert(array(
                'role_id' => $role,
                'employee_id' => $employeeId
            ));
        }
    }
}